//
//  UIImage+Extension.swift
//  SwiftProject
//
//  Created by qindong on 2021/6/8.
//

import Foundation

extension UIImage {
    var width : CGFloat {
        size.width
    }

    var height : CGFloat {
        size.height
    }

    #if DEBUG
    static func awake() {
        swizzledViewControllerMethod()
    }

    class func swizzledViewControllerMethod() {
        let originalSelctor = #selector(UIImage.init(named:))
        let swizzledSelector = #selector(UIImage.withoutNilInit(named:))
        Self.swizzleMethod(for: UIImage.self, originalSelector: originalSelctor, swizzledSelector: swizzledSelector)
    }

    @objc func withoutNilInit(named: String) -> UIImage? {
        if named.isEmpty {
            return nil
        } else {
            return withoutNilInit(named: named)
        }
    }
    #endif

    // MARK: - 在UIImage中心覆盖小的UIimage
    func addSubImage(_ subImage : UIImage, _ ratio : CGFloat = 0.2) -> UIImage {
        let w : CGFloat = width
        let h : CGFloat = height
        let subW : CGFloat = w * ratio
        let subH : CGFloat = h * ratio
        let colorSpace : CGColorSpace = CGColorSpaceCreateDeviceRGB()
        let context : CGContext = CGContext(data: nil, width: Int(w), height: Int(h), bitsPerComponent: 8, bytesPerRow: 4 * Int(w), space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)!
        context.draw(cgImage!, in: CGRect(x: 0, y: 0, width: w, height: h))
        context.draw(subImage.cgImage!, in: CGRect(x: (w - subW) / 2, y: (h - subH) / 2, width: subW, height: subH))
        return UIImage(cgImage: context.makeImage()!)
    }
}
